package com.boot.config;

import com.boot.service.MailService;
import com.boot.utils.PasswordGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDate;

@Component
public class AdminCredentialManager {

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    private AdminCredentials credentials;

    @Value("${spring.mail.username}")
    private String notifyEmail;

    @Resource
    private MailService mailService;

    @PostConstruct
    public void init() {
        String username = PasswordGenerator.generateSecurePassword();
        String rawPassword = PasswordGenerator.generateSecurePassword();

        this.credentials = new AdminCredentials(username, rawPassword, passwordEncoder);

        sendInitialCredentialsEmail(username, rawPassword);
    }

    private void sendInitialCredentialsEmail(String username, String rawPassword) {
        new Thread(() -> {
            try {
                Thread.sleep(2000);

                String subject = "🔐 系统已启动 - 本次管理员登录凭据";
                String content = buildCredentialEmail(username, rawPassword);
                mailService.sendHtmlMail(notifyEmail, subject, content);
                System.out.println("✅ 初始管理员凭据已发送至：" + notifyEmail);
            } catch (Exception e) {
                System.err.println("❌ 邮件发送失败：" + e.getMessage());
                e.printStackTrace();
            }
        }).start();
    }

    private String buildCredentialEmail(String username, String password) {
        return "<div style='font-family:Arial,sans-serif;padding:20px;border:1px solid #ddd;max-width:600px;margin:auto;'>"
                + "<h2 style='color:#4CAF50;'>🚀 系统已启动</h2>"
                + "<p><strong>您好：</strong></p>"
                + "<p>服务已成功启动，本次会话的管理员登录凭据如下（<span style='color:red'>重启后失效</span>）：</p>"
                + "<table style='width:100%;border-collapse:collapse;margin:20px 0;'>"
                + "<tr><td style='padding:8px;border:1px solid #ccc;width:30%;'><strong>用户名</strong></td><td style='padding:8px;border:1px solid #ccc;'>" + username + "</td></tr>"
                + "<tr><td style='padding:8px;border:1px solid #ccc;'><strong>密码</strong></td><td style='padding:8px;border:1px solid #ccc;color:red;font-weight:bold;'>" + password + "</td></tr>"
                + "</table>"
                + "<p style='color:#d32f2f;'>⚠️ 安全提示：此账号为临时内存账号，重启后将重新生成，请勿长期依赖。</p>"
                + "<footer style='margin-top:30px;color:#777;font-size:0.9em;text-align:center;'>"
                + "&copy; " + LocalDate.now().getYear() + " 系统管理平台</footer>"
                + "</div>";
    }

    public AdminCredentials getCredentials() {
        return credentials;
    }
}
